package com.hnas.common.interceptors;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.account.service.AccountService;
import com.hnas.api.dto.DTOResult;
import com.hnas.appLogin.util.AppTypeConstants;
import com.hnas.common.outdto.DTOTokenChecked;
import com.hnas.common.util.ResultCode;
import com.hnas.core.util.StringUtil;

public class AllInterceptor implements HandlerInterceptor {

	private static Log log = LogFactory.getLog(AllInterceptor.class);

	@Autowired
	private AccountService accountService;

	private static ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestUri = request.getRequestURI();
		String intoParams = "";
		Map<String, String[]> map = request.getParameterMap();
		if (null != map && map.size() > 0) {
			Set<Entry<String, String[]>> entrys = map.entrySet();
			for (Entry<String, String[]> entry : entrys) {
				String[] strings = entry.getValue();
				intoParams += entry.getKey() + ":";
				for (String s : strings) {
					intoParams += s + ",";
				}
			}
		}

		DTOResult dtoResult = new DTOResult();
		try {
			// 过滤登录接口
			if (greenChannel(requestUri, dtoResult)) {
				return true;
			}
			DTOTokenChecked dto = new DTOTokenChecked();
			String customData = request.getParameter("customData");
			if (StringUtil.isEmpty(customData)) {
				return printFailResult(response, dtoResult, ResultCode.ERROR_10000);
			}
			JSONObject jo = (JSONObject) JSON.parse(customData);
			String userName = jo.getString("userName");
			String appid = jo.getString("appid");
			if ("com_ykt_android_pos".equals(appid)) {
				dtoResult.setResultCode(ResultCode.SUCCESS);
				dtoResult.setResultMsg("过滤POS发来的请求！！");
				return true;
			}

			if ("com.wxxnk.doudou.app".equals(appid)) {
				dtoResult.setResultCode(ResultCode.SUCCESS);
				dtoResult.setResultMsg("过滤兜兜发来的请求！！");
				return true;
			}
			System.out.println("userName:" + userName);
			if (StringUtil.isEmpty(userName)) {
				System.out.println("拦截入参数据为空");
				return printFailResult(response, dtoResult, ResultCode.ERROR_10000);
			}
			JSONObject jo1 = (JSONObject) JSON.parse(userName);
			dto.setAcc_id(jo1.getString("acc_id"));
			dto.setApp_type(jo1.getString("app_type"));
			dto.setToken(jo1.getString("token"));
			dto.setOpenid(jo1.getString("openid"));
			System.out.println(dto);

			if (StringUtil.isEmpty(dto.getApp_type())) {
				return printFailResult(response, dtoResult, ResultCode.ERROR_098);
			}

			if (StringUtil.isEmpty(dto.getToken())) {
				return printFailResult(response, dtoResult, ResultCode.ERROR_106);
			}

			if (AppTypeConstants.WXXNK.equals(dto.getApp_type())) {// 微信虚拟卡请求
				if (StringUtil.isEmpty(dto.getOpenid())) {
					return printFailResult(response, dtoResult, ResultCode.ERROR_001);
				}
			}

			// 检验token是否有效
			String resultCode = accountService.checkedToken(dto);
			if (!ResultCode.SUCCESS.equals(resultCode)) {
				return printFailResult(response, dtoResult, resultCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			log.info("开始请求路径：" + requestUri + ",请求数据:" + intoParams + "返回参数：" + dtoResult);
		}

		return true;
	}

	private boolean greenChannel(String requestUri, DTOResult dtoResult) {
		// 过滤登录接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("login")) {
			return mapperGreen(dtoResult, "过滤登录接口！！");
		}
		// 过滤发送短信验证码接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("verificationCode")) {
			return mapperGreen(dtoResult, "过滤发送短信验证码接口！！");
		}

		// 过滤抢红包接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("register")) {
			return mapperGreen(dtoResult, "过滤注册抢红包接口！！");
		}

		// 过滤领红包接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getRedPacket")) {
			return mapperGreen(dtoResult, "过滤领红包接口！！");
		}

		// 过滤抢红包接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("grabRedPacket")) {
			return mapperGreen(dtoResult, "过滤抢红包接口！！");
		}

		// 过滤邀请码注册接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("invitationRegister")) {
			return mapperGreen(dtoResult, "邀请码注册接口！！");
		}
		
		// 过滤乘车码用户证书申请接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("applyUserCert")) {
			return mapperGreen(dtoResult, "乘车码用户证书申请接口！！");
		}
		// 过滤乘车码交易接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("qrOnBusTrade")) {
			return mapperGreen(dtoResult, "乘车码交易接口！");
		}		
		
		// 查询账户绑定接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("searchActBind")) {
			return mapperGreen(dtoResult, "乘车码查询账户绑定接口！！");
		}
		// 过滤乘车码账户绑定申请接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("accountsBind")) {
			return mapperGreen(dtoResult, "乘车码账户绑定申请接口！！");
		}
		
		// 过滤乘车码账户绑定申请接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getCurrentTime")) {
			return mapperGreen(dtoResult, "乘车码获取核心当前时间接口！！");
		}
		// 乘车扫码主动还款接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("activeRepay")) {
			return mapperGreen(dtoResult, "乘车码主动还款接口！！");
		}
		
		//过滤外围调用微信支付异步通知接口
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("WXPayStatusCallBack")) {
			return mapperGreen(dtoResult, "微信支付异步通知接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("WXPayCallback")) {
			return mapperGreen(dtoResult, "电子卡购卡微信支付回调接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("registerWithChannel")) {
			return mapperGreen(dtoResult, "渠道注册接口！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("ecard/trade/createPosOrder")) {
			return mapperGreen(dtoResult, "电子卡创建POS订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("ecard/trade/notifyPaymentStatus")) {
			return mapperGreen(dtoResult, "POS异步通知接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getSaleCardOrderByOrderNo")) {
			return mapperGreen(dtoResult, "根据订单号查询订单信息接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getCardInfoByShareCode")) {
			return mapperGreen(dtoResult, "根据分享码获取卡信息接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("createShareCode")) {
			return mapperGreen(dtoResult, "创建分享码接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("shareReceiveECard")) {
			return mapperGreen(dtoResult, "领取分享的电子卡接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("registerRecieveECard")) {
			return mapperGreen(dtoResult, "领取分享电子卡注册接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getAllMerchant")) {
			return mapperGreen(dtoResult, "获取商家列表接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getMerchantDetail")) {
			return mapperGreen(dtoResult, "获取商家详情接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("createEntityCardOrder")) {
			return mapperGreen(dtoResult, "创建购实体卡订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getEntityListByAccId")) {
			return mapperGreen(dtoResult, "根据账户id获取购实体卡订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("confirmEntityCardConsume")) {
			return mapperGreen(dtoResult, "确认购实体卡订单消费接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getEntityOrderByOrderNo")) {
			return mapperGreen(dtoResult, "根据订单编号获取购实体卡订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getMrchList")) {
			return mapperGreen(dtoResult, "获取商家列表接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getCommoditListByMrch")) {
			return mapperGreen(dtoResult, "根据商户id获取商品列表接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("createCommoditOrder")) {
			return mapperGreen(dtoResult, "创建购买商品订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getCommoditOrderListByAccId")) {
			return mapperGreen(dtoResult, "根据账户id获取商品购买订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("checkBindEntityCard")) {
			return mapperGreen(dtoResult, "根据卡号检查实体卡是否被绑定过！");
		}
		/*if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("unbindECard")) {
			return mapperGreen(dtoResult, "解绑电子卡接口！！");
		}*/
		/*if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("createSaleCardOrder")) {
			return mapperGreen(dtoResult, "创建电子卡购卡订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("WXPayCallback")) {
			return mapperGreen(dtoResult, "创建电子卡购卡订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("getSaleCardOrderByOrderNo")) {
			return mapperGreen(dtoResult, "根据订单号查询订单信息接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("backCardApply")) {
			return mapperGreen(dtoResult, "电子卡退卡申请接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("checkCardSecretKey")) {
			return mapperGreen(dtoResult, "校验卡秘钥接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("recharge/createRechargeOrder")) {
			return mapperGreen(dtoResult, "电子卡创建充值订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("ecard/trade/createPosOrder")) {
			return mapperGreen(dtoResult, "电子卡创建POS订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("ecard/trade/createQRcodeOrder")) {
			return mapperGreen(dtoResult, "电子卡用户扫商户创建订单接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("ecard/trade/getTradeRecordList")) {
			return mapperGreen(dtoResult, "电子卡查询交易记录接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("receiveOrRefuseECard")) {
			return mapperGreen(dtoResult, "拒绝/领取电子卡接口！！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("queryCardInfoList")) {
			return mapperGreen(dtoResult, "根据账户id和卡状态查询电子卡列表接口！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("sendECard")) {
			return mapperGreen(dtoResult, "赠送电子卡接口！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("registerWithChannel")) {
			return mapperGreen(dtoResult, "渠道注册接口！");
		}
		if (StringUtil.isNotEmpty(requestUri) && requestUri.endsWith("cancelGiveECard")) {
			return mapperGreen(dtoResult, "取消赠送接口！");
		}*/
		return false;
	}

	private boolean mapperGreen(DTOResult dtoResult, String msg) {
		dtoResult.setResultCode(ResultCode.SUCCESS);
		dtoResult.setResultMsg(msg);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	private boolean printFailResult(HttpServletResponse response, DTOResult dtoResult, String code)
			throws IOException, JsonProcessingException {
		dtoResult.setResultCode(code);
		dtoResult.setResultMsg(ResultCode.getResultValue(code));
		response.getWriter().print(objectMapper.writeValueAsString(dtoResult));
		return false;
	}

}
